// The NSpring Framework for .NET
// Copyright (c) 2003, Jeffrey Varszegi
// All rights reserved.
// 
// Redistribution and use in source and binary forms, with or without modification, 
// are permitted provided that the following conditions are met:
// 
// - Redistributions of source code must retain the above copyright notice, this 
// list of conditions and the following disclaimer.
// 
// - Redistributions in binary form must reproduce the above copyright notice, this 
// list of conditions and the following disclaimer in the documentation and/or other 
// materials provided with the distribution.
// 
// - Neither the name of the NSpring project nor the names of its contributors may 
// be used to endorse or promote products derived from this software without 
// specific prior written permission from the copyright owner.
// 
// - No product derived from this software may be called "NSpring", nor may 
// "NSpring" appear in the name of such a product, without specific prior written 
// permission from the copyright owner.
// 
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
// OF THE POSSIBILITY OF SUCH DAMAGE. 

namespace NSpring.Logging.Loggers {

using System;
using System.Collections;
using System.Data;
using System.Text;

using NSpring.Logging;
using NSpring.Logging.Common.Pattern;
using NSpring.Logging.EventFormatters;
using NSpring.Logging.Exceptions;

/// <summary>
/// <para>
/// A logger implementation that writes event information to a database.  An INSERT or UPDATE
/// statement (or a stored-procedure call) is constructed for each event using a pattern set 
/// on the SQLPattern property.
/// </para>
/// <para>
/// The underlying database connection is held open while the logger is open; no other threads
/// should use the same connection.
/// </para>
/// </summary>
public sealed class DatabaseLogger : Logger {
//    private const int MINIMUM_CONNECTION_TIMEOUT        = 1000;
    private const char APOSTROPHE_CHAR                  = '\'';

    private const string APOSTROPHE                     = "'";
    private const string APOSTROPHE_ESCAPE              = "''";

    private bool isTransactionEnabled                   = false;
    private IsolationLevel transactionIsolationLevel    = IsolationLevel.Serializable;
    
    private PatternParser parser                        = new PatternParser(true, true, true, true, true);
    private string sqlPattern                           = null;
    private Token[] expression;
    
    private IDbConnection connection;
    private ConnectionState connectionState             = ConnectionState.Closed;
//    private int connectionTimeout                       = 5000;
    
    /// <summary>
    /// Constructs a new instance.  The connection and SQL pattern must be set before the logger can be opened
    /// </summary>
    public DatabaseLogger() {
        eventFormatter = new XMLEventFormatter();
    }
    
    /// <summary>
    /// Constructs a new instance that will use the specified connection for logging purposes.  
    /// When the logger is opened, it will open the connection.  The SQL pattern must be set before
    /// the logger can be opened
    /// </summary>
    /// <param name="_connection">The connection to use to log messages</param>
    public DatabaseLogger(IDbConnection _connection) {
        connection = _connection;
        eventFormatter = new XMLEventFormatter();
    }
    
    /// <summary>
    /// Constructs a new instance that will use the specified connection and pattern for logging purposes.  
    /// When the logger is opened, it will open the connection
    /// </summary>
    /// <param name="_connection">The connection to use to log messages</param>
    /// <param name="_sqlPattern">The pattern to use when creating SQL statements</param>
    public DatabaseLogger(IDbConnection _connection, string _sqlPattern) {
        connection = _connection;
        sqlPattern = _sqlPattern;
    }
    
    /// <summary>
    /// The database connection used by the logger (cannot be set while the logger is open)
    /// </summary>
    public IDbConnection Connection {
        get {
            lock (monitor) {
                return connection;
            }
        }
        set {
            lock (monitor) {
                if (!isClosed) {
                    throw new ApplicationException("Cannot set this property while the logger is open");
                }
                connection = value;
            }
        }
    }
    
    /*
    /// <summary>
    /// The number of milliseconds that the logger will use as a connection timeout
    /// </summary>
    public int ConnectionTimeout {
        get {
            return connectionTimeout;
        }
        set {
            connectionTimeout = Math.Max(value, MINIMUM_CONNECTION_TIMEOUT);
        }
    }
    */
    
    /// <summary>
    /// An unsynchronized read of the current state of the underlying database connection
    /// </summary>
    public ConnectionState ConnectionState {
        get {
            return connectionState;
        }
    }
    
    /// <summary>
    /// Opens the underlying database connection used by this instance
    /// </summary>
    protected override void AcquireResources() {
        if (connection == null) {
            throw new ApplicationException("No connection set-- cannot start");
        }
        else if (sqlPattern == null) {
            throw new ApplicationException("No SQL pattern set-- cannot start");
        }
        expression = (new PatternParser(true, true, true, true, true)).Parse(sqlPattern);
        
        try {
            connection.Open();
            connectionState = ConnectionState.Open;
        }
        catch (Exception e) {
            try {
                connection.Close();
            } catch {}
            connectionState = ConnectionState.Closed;
            throw e;
        }
    }
    
    /// <summary>
    /// Closes the underlying database connection used by this instance
    /// </summary>
    protected override void ReleaseResources() {
        try {
            connection.Close();
        }
        catch {
            connectionState = ConnectionState.Closed;
        }
        connectionState = ConnectionState.Closed;
    }
    
    /// <summary>
    /// Writes the specified event to the database
    /// </summary>
    /// <param name="_event">The event to write</param>
    protected override void Write(Event _event) {
        IDbTransaction transaction = null;
        try {
            connectionState = connection.State;
            if (connectionState != ConnectionState.Open) {
                connection.Open();
                connectionState = connection.State;
            }

            IDbCommand command = connection.CreateCommand();
            if (isTransactionEnabled) {
                transaction = connection.BeginTransaction(transactionIsolationLevel);
                command.Transaction = transaction;
            }
            command.CommandText = CreateSQL(_event);
            command.ExecuteNonQuery();
            if (transaction != null) {
                transaction.Commit();
            }
        } catch (Exception e) {
            if (transaction != null) {
                try { transaction.Rollback(); } catch {}
            }
            connectionState = connection.State;
            throw new LoggerException(this, _event, e);
        }
    }
    
    /// <summary>
    /// Writes the specified events to the database
    /// </summary>
    /// <param name="events">The events to write</param>
    /// <param name="length">The number of events to write</param>
    protected override void Write(Event[] events, int length) {
        IDbTransaction transaction = null;
        try {
            connectionState = connection.State;
            if (connectionState != ConnectionState.Open) {
                connection.Open();
                connectionState = connection.State;
            }
            IDbCommand command = connection.CreateCommand();
            if (isTransactionEnabled) {
                transaction = connection.BeginTransaction(transactionIsolationLevel);
                command.Transaction = transaction;
            }
            for(int x = 0; x < length; x++) {
                try {
                    command.CommandText = CreateSQL(events[x]);
                    command.ExecuteNonQuery();
                }
                catch (Exception innerException) {
                    ExceptionHandler.Handle(new LoggerException(this, events[x], innerException));
                }
            }
            if (transaction != null) {
                transaction.Commit();
            }
        } catch {
            if (transaction != null) {
                try { transaction.Rollback(); } catch {}
            }
            connectionState = connection.State;
        }
    }
    
    /// <summary>
    /// Gets and sets whether the logger is transaction-enabled.  If set to true,
    /// each event update (or batch of them in buffering mode) will be wrapped in a separate transaction.
    /// </summary>
    public bool IsTransactionEnabled {
        get {
            lock (monitor) {
                return isTransactionEnabled;
            }
        }
        set {
            lock (monitor) {
                if (!isClosed) {
                    throw new ApplicationException("Cannot set this property while the logger is open");
                }
                isTransactionEnabled = value;
            }
        }
    }
    
    /// <summary>
    /// The transaction-isolation level used when transactions are enabled
    /// </summary>
    public IsolationLevel TransactionIsolationLevel {
        get {
            return transactionIsolationLevel;
        }
        set {
            transactionIsolationLevel = value;
        }
    }
    
    /// <summary>
    /// The pattern to use when creating SQL statements.  This pattern must include
    /// single quotes around every value that may contain apostrophes (the logger will
    /// take care of escaping the values themselves).
    /// </summary>
    public string SQLPattern {
        get {
            lock (monitor) {
                return sqlPattern;
            }
        }
        set {
            lock (monitor) {
                if (value == null) {
                    throw new ArgumentNullException();
                }
                expression = parser.Parse(value);
                sqlPattern = value;
            }
        }
    }

    private string CreateSQL(Event _event) {
        StringBuilder sb = new StringBuilder(128);
        Token[] tokens = expression;
        Token token;
        for(int x = 0; x < tokens.Length; x++) {
            token = tokens[x];
            switch (token.Type) {
                case TokenType.Text : {
                    sb.Append(token.Text);
                    break;
                }
                case TokenType.Separator : {
                    sb.Append(token.Text);
                    break;
                }
                case TokenType.ContextProperty : {
                    sb.Append(EscapeSQL(token.Format(_event)));
                    break;
                }
                case TokenType.EventProperty : {
                    sb.Append(EscapeSQL(token.Format(_event)));
                    break;
                }
                case TokenType.Event : {
                    sb.Append(EscapeSQL(eventFormatter.Format(_event)));
                    break;
                }
                case TokenType.Message : {
                    sb.Append(EscapeSQL(token.Format(_event)));
                    break;
                }
                case TokenType.Data : {
                    if (_event.Data != null) {
                        eventFormatter.DataFormatter.Format(_event.Data, sb);
                    }
                    break;
                }
            }
        }
        return sb.ToString();
    }
    
    private static string EscapeSQL(string s) {
        if (s.IndexOf(APOSTROPHE_CHAR) >= 0) {
            s = s.Replace(APOSTROPHE, APOSTROPHE_ESCAPE);
        }
        return s;
    }
    
}

}
